<?php

class User_Backend_Security_Add extends User_Backend_Security_Edit 
{
    
    protected function _initElements()
    {
        parent::_initElements();
        
        $this->_addElement('email', array('validators' => array('email')));
        $this->_addElement('password1', 'password', array(
            'caption' => __('PASSWORD'), 
            'validators' => array('password'),
        ));
        $this->_addElement('password2', 'password', array(
            'caption' => __('CONFIRM_PASSWORD'), 
            ));
        $this->_setAsRequired('email', 'password1', 'password2');
    }
    
    protected function _insert() 
    {
        $subject_id = call_user_func_array(array('Security_Utils_Subject', 'create'), 
            array_extract($this->_getValues(), array('email', 'password1')));
        
        $this->_setValue('subject_id', $subject_id);
        
        parent::_insert();
    }
    
    /**
    * @desc Simple form jumps here in case of DB-exception. Can be used for
    * callback actions, e.g. to build link for duplicate entry only if exception 
    * raised. 
    * 
    */
    protected function _exceptionCallback() 
    {
        $this->_map(MySQL::ER_DUP_ENTRY, __('ADMIN_ER_DUP_ENTRY', $this->_duplicateLink()));
    }
    
    /**
    * @desc Make link in case of duplicate entry.
    * 
    * @return string 
    */
    protected function _duplicateLink() 
    {
        $query = '
            SELECT 
                   `s_a`.`id` 
              FROM 
                   `system_subject` `s_s`, `system_admin` `s_a` 
             WHERE 
                   `s_a`.`subject_id` = `s_s`.`id` 
               AND 
                   `s_s`.`email` = "' . database::escape($this->_getValue('email')) . '"
            ';
        extract(Backend_Filter_Structure::get());
        return 
            sprintf('?lang=%s&section=%d&module=%s&manager=%s&action=edit&id=%d', 
            $lang, $section, $module, $manager, database::fetchOne($query));
    }
    
}